package com.yanqu.road.server.manager.tomb.timer;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.pb.tomb.Tomb;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.tomb.TombActivity;
import com.yanqu.road.server.manager.tomb.TombServiceMgr;
import com.yanqu.road.server.manager.tomb.entity.DbActivityTombInfo;
import com.yanqu.road.server.manager.tomb.entity.DbTombServerData;
import com.yanqu.road.server.manager.tomb.entity.UserAbilityInfo;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.sync.message.SyncResponse;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.executor.GeneralTask;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

public class TombTask extends GeneralTask {
    private static Logger logger = LogManager.getLogger(TombTask.class.getName());

    @Override
    public void doRun() {
        for (TombActivity tombActivity : TombServiceMgr.getActivityMap().values()) {

            boolean isShowTime = false;
            ActivityInfo activityInfo = tombActivity.getActivityInfo();
            long nowSecondTimestamp = System.currentTimeMillis() / 1000;

            if (nowSecondTimestamp > activityInfo.getEndShowTime() + DateHelper.DAY_SECONDS) {
                TombServiceMgr.getActivityMap().remove(activityInfo.getActivityId());
                continue;
            }

            if (nowSecondTimestamp > activityInfo.getBeginShowTime()) {
                isShowTime = true;
            }

            boolean isGenerateActivityEventNumTime = false;
            //展示期半小时后，开始初始化
            if (nowSecondTimestamp > activityInfo.getBeginShowTime() + 30 * 60) {
                isGenerateActivityEventNumTime = true;
            }

            for (Map.Entry<Integer, DbActivityTombInfo> tombInfoEntry : tombActivity.getDbActivityTombInfoMap().entrySet()) {
                int groupId = tombInfoEntry.getKey();

                DbActivityTombInfo dbActivityTombInfo = tombInfoEntry.getValue();

                List<Long> serverIdList = TombServiceMgr.getServerIdSet(activityInfo, groupId);
                //List<Long> serverIdList = activityInfo.getServerIdList();
                //是否获取到所有服务器数据
                boolean allReady = true;
                for (long serverId : serverIdList) {
                    DbTombServerData dbTombServerData = tombActivity.getDbData().getDbTombServerData(tombActivity.getActivityInfo().getActivityId(), serverId, groupId);
                    if (dbTombServerData.getActivityUserNum() < 0) {
                        allReady = false;
                        if (isGenerateActivityEventNumTime) {
                            logger.info("秦始皇陵墓正在从其它服务器拉取活跃用户数量, 分组 {}， serverId {}", groupId, dbTombServerData.getServerId());

                            Tomb.TombServerTopPatronsReq.Builder req = Tomb.TombServerTopPatronsReq.newBuilder();
                            req.setActivityId(activityInfo.getActivityId());
                            req.setGroupId(groupId);

                            Tomb.TombServerDataResp.Builder builder = Tomb.TombServerDataResp.newBuilder();
                            CompletableFuture<SyncResponse> syncResponseFuture = MessageHelper.sendToGameServer(serverId, GameProtocol.S_TOMB_SERVER_DATA_CROSS_TO_GAME, tombActivity.getActivityInfo().getActivityId(), 0, req, builder);
                            syncResponseFuture.thenAccept(syncResponse -> {
                                if(syncResponse.getErrorCode() == GameErrorCode.E_ERROR_TIME_OUT){
                                    logger.info("秦始皇陵墓处理其它服务器拉取活跃用户数量的返回信息 ！！！ 超时  group {}, server {}", groupId, serverId);
                                }else {
                                    logger.info("秦始皇陵墓处理其它服务器拉取活跃用户数量的返回信息");
                                    dbTombServerData.setActivityUserNum(builder.getActivityNum());
                                    List<Integer> tombEventNumParam = tombActivity.getConfig().getConfig().getTOMB_EVENT_NUM_PARAM();
                                    int p2 = tombEventNumParam.get(1);
                                    int totalActivityNum = tombActivity.getDbData().generateTotalActivityNum(tombActivity.getActivityInfo().getActivityId());
                                    dbActivityTombInfo.setGenerateEventNum(totalActivityNum * p2);
                                    dbActivityTombInfo.setUpdateOption();
                                }
                            });
                        }
                    }
                }


                //是否在游戏时间
                boolean isGameBegin = false;
                long beginTime = tombActivity.getActivityInfo().getBeginTime();
                if (nowSecondTimestamp > beginTime) {
                    int openTime = tombActivity.getConfig().getConfig().getTOMB_DAILY_OPEN_TIME();
                    int endTime = tombActivity.getConfig().getConfig().getTOMB_DAILY_END_TIME();

                    int hour = DateHelper.getTimeStampHours(nowSecondTimestamp * 1000);
                    if (hour >= openTime && hour < endTime) {
                        isGameBegin = true;
                    }
                }

                logger.info("秦始皇陵墓定时器，activityId: {}, 分组：{}， isAllReady: {} isShowTime: {}, isGameTime: {}, isGenerateActivityNumTime: {}, 事件数总: {}", tombActivity.getActivityInfo().getActivityId(), groupId, allReady, isShowTime, isGameBegin, isGenerateActivityEventNumTime, dbActivityTombInfo.getGenerateEventNum());
                if (!isShowTime) {
                    continue;
                }

                if (!tombActivity.getInitialized(groupId)) {
                    if (allReady) {
                        logger.info("秦始皇陵墓地图");
                        tombActivity.generateMaze(groupId);
                        tombActivity.setInitialized(groupId, true);
                        logger.info("秦始皇陵墓地图初始化完成!");
                    }
                }

                if (tombActivity.getInitialized(groupId)) {
                    int nowNum = tombActivity.getHeartbeat().getList(groupId).size();
                    int allNum = tombActivity.getDbData().getDbTombUserByGroupId(groupId).size();
                    logger.info("秦始皇陵墓，活动 {} ， 分组 {} 活动玩家{}人，当前活跃玩家{}人，当前已探索到第{}层，当前最高{}层，秦始皇BOSS在第{}层", tombActivity.getActivityInfo().getActivityId(), groupId, allNum, nowNum, dbActivityTombInfo.getMaxExploreFloor(), dbActivityTombInfo.getMaxFloor(), dbActivityTombInfo.getBossFloor());
                    tombActivity.generateMaze(groupId);
                    tombActivity.clearDbTombPosition(groupId);
//                tombActivity.clearPositionMapData();
                    //检测不在活动的玩家，从地图清出去
                    tombActivity.checkOffline();
                }

                for (long serverId : serverIdList) {
                    DbTombServerData dbTombServerData = tombActivity.getDbData().getDbTombServerData(tombActivity.getActivityInfo().getActivityId(), serverId, groupId);
                    if (DateHelper.isSameDay(dbTombServerData.getUpdateTime() / 1000, nowSecondTimestamp)) {
                        continue;
                    }
                    //这里获取参于服的门客数据
                    logger.info("秦始皇陵墓正在从其它服务器拉取玩家门客数据 groupId {} serverId {}", groupId, dbTombServerData.getServerId());
                    Tomb.TombServerTopPatronsReq.Builder req = Tomb.TombServerTopPatronsReq.newBuilder();
                    req.setActivityId(activityInfo.getActivityId());
                    req.setGroupId(groupId);
                    Tomb.TombServerTopPatronsResp.Builder builder = Tomb.TombServerTopPatronsResp.newBuilder();
                    CompletableFuture<SyncResponse> syncResponseFuture = MessageHelper.sendToGameServer(serverId, GameProtocol.S_TOMB_SERVER_TOP_PATRONS_CROSS_TO_GAME, tombActivity.getActivityInfo().getActivityId(), 0, req, builder);
                    syncResponseFuture.thenAccept(syncResponse -> {
                        if(syncResponse.getErrorCode() == GameErrorCode.E_ERROR_TIME_OUT){
                            logger.info("秦始皇陵墓正在处理从其它服务器拉取玩家门客数据！！！ 超时  group {}, server {}", groupId, serverId);
                        }else {
                            logger.info("秦始皇陵墓正在处理从其它服务器拉取玩家门客数据");
                            dbTombServerData.getData().clear();
                            for (Tomb.UserAbilityTemp.Builder temp : builder.getListBuilderList()) {
                                UserAbilityInfo userAbilityInfo = UserAbilityInfo.newInstance(temp.build());
                                dbTombServerData.getData().add(userAbilityInfo);
                            }
                            dbTombServerData.refreshUpdateTime();
                            tombActivity.getDbData().refreshUserAbilityRanking(groupId);
                            tombActivity.getDbData().generateNpcBaseBlood(groupId);
                        }
                    });

                }
            }
        }
    }
}